package com.ai.chat.service.impl;

import com.ai.chat.model.dto.ChatRequestDTO;
import com.ai.chat.model.dto.ChatResponseDTO;
import com.ai.chat.service.ChatService;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
@Slf4j
public class ChatServiceImpl implements ChatService {

    private final RestTemplate restTemplate;
    private final RedisTemplate<String, Object> redisTemplate;

    @Value("${app.deepseek.base-url}")
    private String deepseekBaseUrl;

    @Value("${app.deepseek.api-key}")
    private String deepseekApiKey;

    private static final String CHAT_HISTORY_KEY = "chat:history:";
    private static final long HISTORY_EXPIRE_DAYS = 30;

    @Override
    @Async
    public CompletableFuture<ChatResponseDTO> sendMessage(ChatRequestDTO request) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                // 创建HTTP头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                headers.set("Authorization", "Bearer " + deepseekApiKey);

                // 构建请求体
                Map<String, Object> requestBody = new HashMap<>();
                requestBody.put("model", "deepseek-r1");
                requestBody.put("messages", Arrays.asList(
                    Collections.singletonMap("role", "user"),
                    Collections.singletonMap("content", request.getContent())
                ));
                requestBody.put("stream", false);

                // 发送请求
                HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
                ResponseEntity<String> response = restTemplate.postForEntity(
                    deepseekBaseUrl, entity, String.class);

                // 处理响应
                if (response.getStatusCode().is2xxSuccessful()) {
                    String responseBody = response.getBody();
                    log.info("DeepSeek API response: {}", responseBody);

                    // 解析响应（实际项目中应使用实体类解析）
                    Map<String, Object> resultMap = JSON.parseObject(responseBody);
                    List<Map<String, Object>> choices = (List<Map<String, Object>>) resultMap.get("choices");
                    if (choices != null && !choices.isEmpty()) {
                        Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message");
                        String content = (String) message.get("content");

                        ChatResponseDTO chatResponse = new ChatResponseDTO();
                        chatResponse.setSessionId(request.getSessionId());
                        chatResponse.setContent(content);
                        chatResponse.setTimestamp(System.currentTimeMillis());

                        // 保存聊天记录
                        saveChatHistory(request.getSessionId(), request, chatResponse);

                        return chatResponse;
                    }
                }

                // 处理API调用失败情况
                ChatResponseDTO errorResponse = new ChatResponseDTO();
                errorResponse.setSessionId(request.getSessionId());
                errorResponse.setContent("抱歉，暂时无法获取AI响应，请稍后再试。");
                errorResponse.setTimestamp(System.currentTimeMillis());
                return errorResponse;

            } catch (Exception e) {
                log.error("调用DeepSeek API失败", e);
                ChatResponseDTO errorResponse = new ChatResponseDTO();
                errorResponse.setSessionId(request.getSessionId());
                errorResponse.setContent("系统错误：" + e.getMessage());
                errorResponse.setTimestamp(System.currentTimeMillis());
                return errorResponse;
            }
        });
    }

    @Override
    @Async
    public CompletableFuture<String> getChatHistory(String sessionId) {
        return CompletableFuture.supplyAsync(() -> {
            // 从Redis获取聊天历史
            String historyKey = CHAT_HISTORY_KEY + sessionId;
            List<Object> historyList = redisTemplate.opsForList().range(historyKey, 0, -1);

            if (historyList != null && !historyList.isEmpty()) {
                return JSON.toJSONString(historyList);
            }
            return "[]";
        });
    }

    @Override
    public void saveChatHistory(String sessionId, ChatRequestDTO request, ChatResponseDTO response) {
        try {
            String historyKey = CHAT_HISTORY_KEY + sessionId;

            // 保存用户消息
            Map<String, Object> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", request.getContent());
            userMessage.put("timestamp", request.getTimestamp());
            redisTemplate.opsForList().rightPush(historyKey, userMessage);

            // 保存AI消息
            Map<String, Object> aiMessage = new HashMap<>();
            aiMessage.put("role", "assistant");
            aiMessage.put("content", response.getContent());
            aiMessage.put("timestamp", response.getTimestamp());
            redisTemplate.opsForList().rightPush(historyKey, aiMessage);

            // 设置过期时间
            redisTemplate.expire(historyKey, HISTORY_EXPIRE_DAYS, TimeUnit.DAYS);

            // TODO: 同时保存到数据库，实现持久化存储

        } catch (Exception e) {
            log.error("保存聊天历史失败", e);
        }
    }
}